package com.hfh.main.user.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hfh.main.common.annotate.JwtToken;
import com.hfh.main.common.resp.Result;
import com.hfh.main.user.entity.UserEntity;
import com.hfh.main.user.mapper.UserMapper;
import com.hfh.main.user.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 用户管理
 * </p>
 */
@Tag(name="用户管理")
@RestController
@RequestMapping("/userEntity")
public class UserController {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserService userService;

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @JwtToken
    @Operation(summary = "用户管理-列表-分页")
    @PostMapping("/listPageUser")
    public Result<?> listPageUser(@RequestParam Integer page, @RequestParam Integer pageSize, @RequestParam Integer role) {
        //分页参数
        Page<UserEntity> rowPage = new Page(page, pageSize);
        //queryWrapper组装查询where条件
        LambdaQueryWrapper<UserEntity> queryWrapper = new LambdaQueryWrapper<>();
        if (role == 1) {
            queryWrapper.eq(UserEntity::getRole, role);
        }
        if (role > 1) {
            queryWrapper.ge(UserEntity::getRole, role);
        }
        rowPage = userMapper.selectPage(rowPage, queryWrapper);
        return Result.success("数据请求成功", rowPage);
    }

    @JwtToken
    @Operation(summary = "用户管理-查询-编号")
    @PostMapping("/selectUserByID/{param}")
    public Result<?> selectUserByID(@PathVariable @Validated String param) {
        QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(("user_id"), param);
        if (userService.count(wrapper) == 0) return Result.failure(200, "编号不存在", sdf.format(new Date()));
        return Result.success(userService.getOne(wrapper));
    }

    @JwtToken
    @Operation(summary = "用户管理-查询-名称")
    @PostMapping("/selectUserByName/{param}")
    public Result<?> selectUserByName(@PathVariable @Validated String param) {
        QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(("user_name"), param);
        if (userService.count(wrapper) == 0) return Result.failure(200, "名称不存在", sdf.format(new Date()));
        return Result.success(userService.getOne(wrapper));
    }

    @JwtToken
    @Operation(summary = "用户管理-查询-学号、名字双重模糊查询")
    @PostMapping("/queryUserByNameOrNo/{param}")
    public Result<?> selectUserByNameOrNo(@PathVariable @Validated String param) {
        QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();
        wrapper.ne("user_role", 1); // 角色非老师、管理员
        wrapper.and(i -> i.like(("user_name"), param)
                .or().like(("user_acc"), param));
        //无值返回空数组
        if (userService.count(wrapper) == 0) return Result.failure(200, "名称不存在", sdf.format(new Date()));
        return Result.success(userService.list(wrapper));
    }

    @JwtToken
    @Operation(summary = "用户管理-查询角色为1的名字模糊查询")
    @PostMapping("/queryTeacherByName/{param}")
    public Result<?> queryTeacherByName(@PathVariable @Validated String param) {
        QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("user_role", 1); // 角色老师、管理员
        wrapper.like(("user_name"), param);
        if (userService.count(wrapper) == 0) return Result.failure(200, "名称不存在", sdf.format(new Date()));
        return Result.success(userService.list(wrapper));
    }

    @JwtToken
    @Operation(summary = "用户管理-查询-账号")
    @PostMapping("/selectUserByAcc/{param}")
    public Result<?> selectUserByAcc(@PathVariable @Validated String param) {
        QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(("user_acc"), param);
        if (userService.count(wrapper) == 0) return Result.failure(200, "账号不存在", sdf.format(new Date()));
        return Result.success(userService.getOne(wrapper));
    }

    @JwtToken
    @Operation(summary = "用户管理-保存")
    @PostMapping("/insert")
    public Result<?> insertUser(@RequestBody @Validated UserEntity entity) {
        QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(("user_id"), entity.getId());
        if (userService.count(wrapper) != 0) return Result.failure(200, "编号已存在", sdf.format(new Date()));
        if (userService.save(entity)) return Result.success("保存成功", sdf.format(new Date()));
        return Result.failure(200, "保存失败", sdf.format(new Date()));
    }

    @JwtToken
    @Operation(summary = "用户管理-删除")
    @PostMapping("/delete/{param}")
    public Result<?> deleteUser(@PathVariable @Validated String param) {
        QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(("user_id"), param);
        if (userService.count(wrapper) == 0) return Result.failure(200, "编号不存在", sdf.format(new Date()));
        if (userService.remove(wrapper)) return Result.success("删除成功", sdf.format(new Date()));
        return Result.failure(200, "删除失败", sdf.format(new Date()));
    }

    @JwtToken
    @Operation(summary = "用户管理-修改")
    @PostMapping("/update")
    public Result<?> updateUser(@RequestBody @Validated UserEntity entity) {
        QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(("user_id"), entity.getId());
        if (userService.count(wrapper) == 0) return Result.failure(200, "编号不存在", sdf.format(new Date()));
        if (userService.updateById(entity)) return Result.success("修改成功", sdf.format(new Date()));
        return Result.failure(200, "修改失败", sdf.format(new Date()));
    }

    @Operation(summary = "用户管理-导出数据")
    @PostMapping("exportExcel")
    public void exportExcelUser(HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("Excel数据表", StandardCharsets.UTF_8).replaceAll("\\+", "%20");
        List<UserEntity> list = userService.list();
        response.setHeader("Content-disposition", "attachment;filename*=" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), UserEntity.class).sheet("Excel数据表").doWrite(list);
    }

    @Operation(summary = "用户管理-导入数据")
    @PostMapping("/importExcel")
    public Result<?> importExcelUser(MultipartFile file) {
        try {
            //获取文件的输入流
            InputStream inputStream = file.getInputStream();
            List<UserEntity> list = EasyExcel.read(inputStream) //调用read方法
                    //注册自定义监听器，字段校验可以在监听器内实现
                    //.registerReadListener(new UserListener())
                    .head(UserEntity.class) //对应导入的实体类
                    .sheet(0) //导入数据的sheet页编号，0代表第一个sheet页，如果不填，则会导入所有sheet页的数据
                    .headRowNumber(1) //列表头行数，1代表列表头有1行，第二行开始为数据行
                    .doReadSync();//开始读Excel，返回一个List<T>集合，继续后续入库操作
            //模拟导入数据库操作
            for (UserEntity entity : list) {
                userService.saveOrUpdate(entity);
            }
            return Result.success("导入成功", sdf.format(new Date()));
        } catch (IOException exception) {
            throw new RuntimeException(exception);
        }
    }

}
